package com.xue.web.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class FileUploadUtil {
    /**
     * @param req         http 请求
     * @param realPath    获取文件路径名
     * @param httpServlet 传个父类
     * @return 上传文件信息
     */
    public static Map<String, String> upLoad(HttpServletRequest req, String realPath, HttpServlet httpServlet) throws IOException {
        //判断是否为文件
        if (!ServletFileUpload.isMultipartContent(req)) {
            return null;
        }
        //创建一个工厂
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        //上传核心组件
        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
        Map<String, String> uploadInformation = new LinkedHashMap<>();
        String videoName, videKey;
        //解析请求
        try {
            List<FileItem> files = fileUpload.parseRequest(req);
            for (FileItem fileItem : files) {
                //判断表单是否为普通表单
                if (fileItem.isFormField()) {
                    videKey = fileItem.getFieldName();
                    videoName = fileItem.getString();
                    uploadInformation.put(videKey, videoName);
                } else {//表单为文件
                    String fileName = fileItem.getName();//获取文件名称
                    String suffix = StringUtils.getSuffix(fileName);
                    InputStream inputStream = fileItem.getInputStream();
                    //生成随机文件名称
                    String randomStr = SnowFlakeUtil.getRandomStr();

                    if (suffix.equalsIgnoreCase(".png") || suffix.equalsIgnoreCase(".jpg")) {

                        uploadInformation.put("imgName", randomStr + suffix);
                    }
                    if (suffix.equalsIgnoreCase(".mp4") || suffix.equalsIgnoreCase(".avi")) {

                        uploadInformation.put("videoName", randomStr + suffix);
                    }

                    //获取服务器文件夹
                    String path = httpServlet.getServletContext().getRealPath("/" + realPath);
                    File file = new File(path, randomStr + suffix);

                    //创建输出流
                    OutputStream outputStream = Files.newOutputStream(file.toPath());
                    //将输入流中的数据写入输入出流中
                    int len = -1;
                    byte[] buff = new byte[1024 * 1024 * 100];
                    while ((len = inputStream.read(buff)) != -1) {
                        outputStream.write(buff, 0, len);
                    }
                    //关闭流
                    inputStream.close();
                    outputStream.close();
                }
            }
        } catch (FileUploadException | IOException e) {
            throw new IOException("解析请求时异常");
        }

        if (uploadInformation.size() != 3) {
            throw new IOException("文件输入不合法");
        } else {
            return uploadInformation;
        }
    }

}
